<template>

    <t-upload
            ref="uploadRef1"
            v-model="files"
            :action="uploadUrl"
            :headers="{authorization:'Bearer '+userStore.token }"
            name="files"
            :placeholder="description"
            :multiple="multiple"
            :auto-upload="autoUpload"
            accept=".jpg,.jpeg,.png"
            :upload-all-files-in-one-request="uploadInOneRequest"
            :is-batch-upload="isBatchUpload"
            :size-limit="{ size: 2, unit: 'MB' }"
            :max="1"
            :disabled="disabled"

            @select-change="handleSelectChange"
            @fail="handleFail"
            @success="handleSuccess"
            @one-file-success="onOneFileSuccess"
            @validate="onValidate"
          />




</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import {
  MessagePlugin,
  UploadInstanceFunctions,
  UploadProps,
  UploadSelectChangeContext,
  ButtonProps,
} from 'tdesign-vue-next';
// import { CloseIcon } from 'tdesign-icons-vue-next';
import { useUserStore } from '@/store';

const emits=defineEmits(['success'])
const userStore=useUserStore()
const uploadUrl=ref(import.meta.env.VITE_API_URL+'/api/storage/local')
const description=ref('请选择上传的图像')
const multiple = ref(false);
const autoUpload = ref(true);
const uploadRef1 = ref<UploadInstanceFunctions>();

const files = ref<UploadProps['value']>([
  // {
  //   name: '这是一个默认文件',
  //   status: 'success',
  //   url: 'https://tdesign.gtimg.com/site/source/figma-pc.png',
  //   size: 1000,
  // },
]);


const uploadInOneRequest = ref(false);

const isBatchUpload = ref(false);
const disabled = ref(false);

const handleFail: UploadProps['onFail'] = ({ file }) => {
  MessagePlugin.error(`文件 ${file.name} 上传失败`);
};
function handleSelectChange(files: File[], context: UploadSelectChangeContext) {
  console.log('onSelectChange', files, context);
}
const handleSuccess: UploadProps['onSuccess'] = (params) => {
  console.log('success', params);
  emits('success',params.response.result[0].url)
  MessagePlugin.success('上传成功');
};

// 多文件上传，一个文件一个请求场景，每个文件也会单独触发上传成功的事件
const onOneFileSuccess: UploadProps['onOneFileSuccess'] = (params) => {
  console.log('onOneFileSuccess', params);
};

// 有文件数量超出时会触发，文件大小超出限制、文件同名时会触发等场景。注意如果设置允许上传同名文件，则此事件不会触发
const onValidate: UploadProps['onValidate'] = (params) => {
  const { files, type } = params;
  console.log('onValidate', type, files);
  const messageMap = {
    FILE_OVER_SIZE_LIMIT: '文件大小超出限制，已自动过滤',
    FILES_OVER_LENGTH_LIMIT: '文件数量超出限制，仅上传未超出数量的文件',
    // if you need same name files, setting allowUploadDuplicateFile={true} please
    FILTER_FILE_SAME_NAME: '不允许上传同名文件',
    BEFORE_ALL_FILES_UPLOAD: 'beforeAllFilesUpload 方法拦截了文件',
    CUSTOM_BEFORE_UPLOAD: 'beforeUpload 方法拦截了文件',
  };
  // you can also set Upload.tips and Upload.status to show warning message.
  messageMap[type] && MessagePlugin.warning(messageMap[type]);
};

</script>

<style>
</style>
